<template>
  <a-select ref="selectRef" v-model:value="selected" style="min-width: 100px">
    <template #notFoundContent>
      <a-spin v-if="fetching" size="small" />
    </template>
    <a-select-option v-for="option in options" :key="option.uid" :value="option.uid"
      >{{ option.name }}
    </a-select-option>
  </a-select>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'

import { useWarehouseApi } from '@/api/chunfeng/wms/warehouse'

interface Option {
  name: string
  uid: string
}

const { queryWarehouse } = useWarehouseApi()

export default defineComponent({
  name: 'WarehouseSelection',
  props: {
    value: {
      type: String,
      required: false,
      default: '',
    },
    preload: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  emits: ['warehouseSelected'],
  setup(props, context) {
    const selected = ref(props.value)
    const options = ref(Array<Option>())
    const fetching = ref(false)

    const filterOption = ref<Boolean | ((string, any) => Boolean)>(false)

    if (props.preload) {
      preload()
      // filterOption.value = (input: string, option: any) => {
      //   console.log(`filter option:[${JSON.stringify(option)}]`)
      //   return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
      // }
    }
    const selectRef = ref()

    watch(
      () => props.value,
      (newValue) => {
        selected.value = newValue
      },
    )
    watch(selected, (newValue) => {
      context.emit('warehouseSelected', newValue)
    })

    // const func = (data: string) =>
    //   executeQueryRequest(queryCustomer({ enabled: true, name: data }), (result: Option[]) => {
    //     options.value = result
    //     fetching.value = false
    //   })
    //
    // const search = debounce(func, 300)
    //
    // function debouncedSearch(data: string) {
    //   if (data) {
    //     options.value.length = 0
    //     fetching.value = true
    //     search(data)
    //   }
    // }

    async function preload() {
      const warehouses = await queryWarehouse({ enabled: true })
      options.value = warehouses.map((value) => ({
        uid: value.uid,
        name: value.name,
      }))
    }

    function reset() {
      selected.value = ''
    }

    return {
      selected,
      options,
      reset,
      fetching,
      selectRef,
      filterOption,
    }
  },
})
</script>
